<template>
  <div class="cost-summary">
    <ProTable
      ref="manual_table"
      :immediate="false"
      :search-form="formList"
      :columns="columns"
      :request="querySettleLettersDetailList"
      :before-search-submit="beforeSearchSubmit"
      :pagination="true"
    >
      <template #extra>
        <Authc permissions="trade:settlement:report:adjustSheet:edit">
          <Button type="primary" @click="importSettleLetters">手工录入</Button>
        </Authc>
        <Authc permissions="trade:settlement:report:adjustSheet:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>
    </ProTable>

    <Modal v-model="importSettleLettersModal" :visible.sync="importSettleLettersModal" title="手工调整">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">
          <FormItem label="对账周期：">
            <DatePicker type="daterange" v-model="dataModule.dateRange" ref="dealDatePicker" split-panels transfer placeholder="对账周期" @on-change="changeDateRange"></DatePicker>
          </FormItem>
          <FormItem label="对账函：" prop="merchantCode">
            <Select v-model="dataModule.settle_letters_code" :label-in-value="true" filterable clearable @on-change="changeParenLetters">
              <Option v-for="(item, index) in parenLettersList" :key="index" :value="item.settle_letters_code">{{ item.settle_letters_code }}</Option>
            </Select>
          </FormItem>

          <FormItem label="商户对账函：" prop="sub_settle_letters_code">
            <Select v-model="dataModule.sub_settle_letters_code" :label-in-value="true" filterable clearable @on-change="changeChildLetters">
              <Option v-for="(item, index) in childLettersList" :key="index" :value="item.sub_settle_letters_code">{{ item.sub_settle_letters_code }}-{{ item.merchantName }}</Option>
            </Select>
          </FormItem>
          <FormItem label="销售金额："  prop="total_order_amount">
            <Input type="number" number v-model="dataModule.total_order_amount" placeholder="请填写，销售金额" >
              <span slot="append">分</span>
            </Input>
          </FormItem>
          <FormItem label="优惠金额：" prop="total_discount">
            <Input type="number" number v-model="dataModule.total_discount" placeholder="请填写，优惠金额" >
              <span slot="append">分</span>
            </Input>
          </FormItem>
          <FormItem label="结算金额：" prop="total_productCost">
            <Input type="number" number v-model="dataModule.total_productCost" placeholder="请填写，结算金额" >
              <span slot="append">分</span>
            </Input>
          </FormItem>
          <FormItem label="服务成功笔数：" prop="scOrderCount">
            <Input type="number" number v-model="dataModule.scOrderCount" placeholder="请填写，服务成功笔数" >
              <span slot="append">笔</span>
            </Input>
          </FormItem>
          <FormItem label="收入：" prop="total_revenue_amount">
            <Input type="number" number v-model="dataModule.total_revenue_amount" placeholder="请填写，收入金额" >
              <span slot="append">分</span>
            </Input>
          </FormItem>
          <FormItem label="调整原因：">
            <Input type="textarea" :rows="4" v-model="dataModule.adjust_note" placeholder="请填写，调整原因" />
          </FormItem>

        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel">取消</Button>
        <Button type="primary" @click="handleSubmit">确定</Button>
      </div>
    </Modal>

    <Modal v-model="uploadSettleLettersModal" :visible.sync="uploadSettleLettersModal" title="上传调整明细">
      <Loading :loading="false">
        <Form ref="uploadSettleLettersModal" :label-width="130" :model="uploadModule" >
          <FormItem label="调整明细上传：">
            <Upload
              :format="['xlsx','xls']"
              :action="uploadPath"
              :on-success="handleUploadSuccess"
              name="file"
              :data="{readType:'AUTH_READ'}">
              <Button icon="ios-cloud-upload-outline">选择文件</Button>
            </Upload>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitUploadCancel">取消</Button>
        <Button type="primary" @click="handleSubmitUpload">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import ProTable from '@/components/ProTable';
import { querySettleLettersDetailList,getOrderDictionary,getMerchantAllMerchant,getMerchantAllOrg,getRevenueType,
  getSettleLetters,adjust, byParentSettleLetter,exportSettleLetters,getUploadPath,uploadAdjustByOriginalLettersCode} from '@/api/statement';
import {getDateYMD,getDateRangeDate} from '@/utils/date';
import util from '@/utils/util'
import {omit} from "lodash";
import Loading from "@/components/Loading";
import appService from '@/utils//appService';
import {Modal} from "view-design";
import Authc from "@/components/Authc";

export default {
  components: {
    // Button,
    Loading,
    ProTable,
    Authc
  },
  data() {
    return {
      importSettleLettersModal:false,
      uploadSettleLettersModal:false,
      parenLettersList:[],
      childLettersList:[],
      dataModule:{
        dateRange:null,
        settle_letters_code:null,
        sub_settle_letters_code:null,
        total_order_amount:null,//调整销售金额
        total_discount:null,//调整优惠金额
        total_productCost:null,//调整结算金额
        scOrderCount:null,//调整销售金额
        total_revenue_amount:null,//调整销售金额
        adjust_note:null,//调整备注
      },
      uploadModule:{
        original_letters_code:null,
        adjust_detail_file:null
      },
      ruleValidate: {
        sub_settle_letters_code: [{ required: true, message: '请选择', trigger: 'change' }],
        total_order_amount: [{ required: true, message: '请填写，且填写整数', type:'integer',min:0,trigger: 'blur' }],
        total_discount: [{ required: true, message: '请填写，且填写整数', type:'integer',min:0,trigger: 'blur' }],
        total_productCost: [{ required: true, message: '请填写，且填写整数', type:'integer',min:0,trigger: 'blur' }],
        scOrderCount: [{ required: true, message: '请填写，且填写整数', type:'integer',min:0,trigger: 'blur' }],
        total_revenue_amount: [{ required: true, message: '请填写，且填写整数', type:'integer',min:0,trigger: 'blur' }],
      },
      formList: [
        {
          type: 'range',
          name: 'date',
          label: '统计周期',
          value: '',
          props: {
            placeholder: '请选择',
            format: 'yyyy年MM月dd日',
            clearable: true
          }
        },
        {
          type: 'select',
          name: 'org_code',
          label: '组织机构',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true,
            filterable: true
          }
        },
        {
          type: 'select',
          name: 'orderSource',
          label: '场景',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true
          }
        },
        {
          type: 'select',
          name: 'revenueType',
          label: '收入确认类型',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: []
          }
        },
        {
          type: 'select',
          name: 'merchantCode',
          label: '商户名称',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true,
            filterable: true
          }
        }
      ],
      columns: [
        {
          title: '收入函编码',
          key: 'settle_letters_code',
          align: 'center',
        },
        {
          title: '收入函子编码',
          key: 'original_letters_code',
          align: 'center',
        },
        {
          title: '收入确认类型',
          key: 'revenue_type_cn',
          align: 'center',
        },
        {
          title: '场景',
          key: 'orderSourceCn',
          align: 'center',
        },
        {
          title: '商户名称',
          key: 'merchantName',
          align: 'center',
        },
        {
          title: '调整销售金额',
          key: 'total_order_amount',
          align: 'center',
        },
        {
          title: '调整优惠金额',
          key: 'total_discount',
          align: 'center',
        },
        {
          title: '调整结算金额',
          key: 'total_productCost',
          align: 'center',
        },
        {
          title: '调整服务成功笔数',
          key: 'scOrderCount',
          align: 'center',
        },
        {
          title: '调整收入',
          key: 'total_revenue_amount',
          align: 'center',
        },
        {
          title: '调整时间',
          key: 'createdDt',
          align: 'center',
        },
        {
          title: '上传明细',
          key: 'detailed',
          align: 'center',
          render: (h, params) => {
            if( appService.hasPermission("trade:settlement:report:adjustSheet:edit")){
              return h('div', [
                h(
                  'a',
                  {
                    on: {
                      click: () => this.uploadFile(params.row)
                    }
                  },
                  '上传'
                )
              ]);
            }else{
              return h('div','无权限');
            }
          }
        },
        {
          title: '下载明细',
          align: 'center',
          render: (h, params) => {
            if(params.row && params.row.adjust_detail_file){
              return h('div', [
                h(
                  'a',
                  {
                    on: {
                      click: () => this.downloadFile(params.row)
                    }
                  },
                  '下载'
                )
              ]);
            }else{
              return h('div','无明细');
            }

          }
        },
        {
          title: '调整原因',
          key: 'adjust_note',
          align: 'center',
        }
      ]
    };
  },
  computed:{
    uploadPath(){
      return getUploadPath
    }
  },
  created() {
    this.initSearchValue()
  },
  methods: {
    querySettleLettersDetailList,
    /**
     * 手工录入-按钮-点击
     */
    importSettleLetters(){
      this.importSettleLettersModal=true
    },
    async handleSubmit(){
      let self=this
      self.$refs['dataModule'].validate(async (valid) => {
        if (valid) {
          adjust(self.dataModule).then(res=>{
            if(res && res.data.ret===0){
              this.$Message.success({
                content: '操作成功！'
              })
              self.handleSubmitCancel()
              //self.refresh()
            }else{
              this.$Message.warning({
                content: res.data.msg||'操作异常！'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSubmitCancel(){
      this.importSettleLettersModal=false
      this.parenLettersList=[]
      this.childLettersList=[]
      this.clearAllModalData()
    },
    /**
     * 结算周期选中改变
     * @param date
     */
    async changeDateRange(date){
      const settle_start = date ? date[0] : '';
      const settle_end = date ? date[1] : '';
      if(settle_start && settle_end){
        const res= await getSettleLetters({
          settle_start,
          settle_end,
          letters_type:0,
        });
        if(res && res.data.ret===0 ){
          this.parenLettersList=res.data.data.list||[]
        }else{
          this.$Message.error("对账周期内未查询到对账函！")
          this.parenLettersList=[]
        }
      }else{
        this.parenLettersList=[]
      }
      this.dataModule.settle_letters_code=null
      this.dataModule.sub_settle_letters_code=null
      this.childLettersList=[]
      this.clearMerchantAmount()
    },
    /**
     * 结算周期选中改变
     * @param date
     */
    async changeParenLetters(item){
      if(item && item.value){
        const res= await byParentSettleLetter(item.value);
        if(res && res.data.ret===0 ){
          this.childLettersList=res.data.data||[]
        }else{
          this.$Message.error("对账周期内未查询到对账函！")
          this.childLettersList=[]
        }
      }
      this.dataModule.sub_settle_letters_code=null
      this.clearMerchantAmount()
    },
    /**
     * 结算周期选中改变
     * @param date
     */
    changeChildLetters(value){
      if(value){
        const selectItemDetail=this.childLettersList.filter(item=>item.sub_settle_letters_code===value.value)
        this.dataModule={
          ...this.dataModule,
          total_order_amount:selectItemDetail[0].total_order_amount,//调整销售金额
          total_discount:selectItemDetail[0].total_discount,//调整优惠金额
          total_productCost:selectItemDetail[0].total_productCost,//调整结算金额
          scOrderCount:selectItemDetail[0].scOrderCount,//调整销售金额
          total_revenue_amount:selectItemDetail[0].total_revenue_amount,//调整销售金额
          adjust_note:selectItemDetail[0].adjust_note,//调整备注
        }
      }else{
        this.clearMerchantAmount()
      }
    },
    /**
     * 晴空商户对账函的金额信息
     */
    clearMerchantAmount(){
      this.dataModule={
        ...this.dataModule,
        total_order_amount:null,//调整销售金额
        total_discount:null,//调整优惠金额
        total_productCost:null,//调整结算金额
        scOrderCount:null,//调整销售金额
        total_revenue_amount:null,//调整销售金额
        adjust_note:null,//调整备注
      }
    },
    clearAllModalData(){
      this.dataModule={
        dateRange:null,
        settle_letters_code:null,
        sub_settle_letters_code:null,
        total_order_amount:null,//调整销售金额
        total_discount:null,//调整优惠金额
        total_productCost:null,//调整结算金额
        scOrderCount:null,//调整销售金额
        total_revenue_amount:null,//调整销售金额
        adjust_note:null,//调整备注
      }
    },
    refresh(){
      this.$refs['manual_table'].onSearch()
    },
    beforeSearchSubmit(data) {
      return omit(data, this.searchDateHandler(data))
    },
    searchDateHandler(data) {
      const {date} = data
      const [startDate, endDate] = getDateRangeDate(date)
      if (startDate) {
        data.settle_start = util.formatDate(startDate)
      }
      if (endDate) {
        data.settle_end = util.formatDate(endDate)
      }
      // 手工调整单
      data.letters_type=1
      console.log('searchDateHandler:',data)
      return data
    },
    async initSearchValue() {
      const orderSourceList = await getOrderDictionary("orderSource")
      const selectOrderSourceList = orderSourceList.map(({value, key}) => {
        return {
          value: key,
          label: value
        };
      });
      this.setSearchOptionListInitValue("orderSource", selectOrderSourceList)

      // 查询商户
      const merchantList = await getMerchantAllMerchant();
      const selectMerchantList = merchantList.map(({merchantCode, merchantName}) => {
        return {
          value: merchantCode,
          label: merchantName
        };
      });
      this.setSearchOptionListInitValue("merchantCode", selectMerchantList)
      // 查询机构
      const orgList = await getMerchantAllOrg();
      const selectOrgList = orgList.map(({organizationCode, organizationName}) => {
        return {
          value: organizationCode,
          label: organizationName
        };
      });
      this.setSearchOptionListInitValue("org_code", selectOrgList)
      const res=await getRevenueType();
      const selectRevenueTypeList = res.map(({revenueType, revenueTypeName}) => {
        return {
          value: revenueType,
          label: revenueTypeName
        };
      });
      this.setSearchOptionListInitValue("revenueType",selectRevenueTypeList)
    },
    uploadFile(row) {
      if(row && row.adjust_detail_file){
        Modal.confirm({
          title: "以上传过明细，再次上传将覆盖原有文件，确定继续？",
          onOk: () => {
            this.openUploadModal(row)
          }
        });
      }else{
        this.openUploadModal()
      }

    },
    openUploadModal(row){
      this.uploadSettleLettersModal=true
      this.uploadModule.original_letters_code=row.original_letters_code
    },
    handleSubmitUploadCancel(){
      this.uploadSettleLettersModal=false
      this.uploadModule={
        original_letters_code:null,
        file_path:null
      };
    },
    async handleSubmitUpload(){
      this.uploadSettleLettersModal=true
      if(!this.uploadModule.adjust_detail_file){
        this.$Message.error("请选择文件")
        return
      }
      if(!this.uploadModule.original_letters_code){
        this.$Message.error("异常，请重新上传")
        return
      }
      const res=await uploadAdjustByOriginalLettersCode(this.uploadModule)
      if(res && res.data.ret===0 ){
        this.$Message.success("上传成功！")
        this.handleSubmitUploadCancel()
        this.refresh()
      }else{
        this.$Message.error("上传明细异常！")
      }
    },
    async handleUploadSuccess(res, file){
      console.log('handleUploadSuccess:',res, file)
      if(res && res.ret===0){
        this.uploadModule.adjust_detail_file=res.data.url
        this.$Message.success("上传成功,点击确定按钮提交！")
      }
    },
    async downloadFile(row){
      if(row && row.adjust_detail_file){
        console.log('downloadFile:',row)
        appService.downloadFileFromFileSystem(row.adjust_detail_file,`${row.original_letters_code}.xlsx`)
      }
    },
    async exportExcel() {
      let data=this.$refs['manual_table'].getSearchParams()
      const {date} =data
      if(!date || date[0]===''){
        this.$Message.error('请选择查询条件~');
        return
      }
      const res=await exportSettleLetters(this.searchDateHandler(data))
      if (res) {
        util.exportExcle(res, `${data.settle_start}至${data.settle_end}手工调整单`);
      }
    },
    setSearchOptionListInitValue(name,value){
      this.formList.map(item=>{
        if(item.name===name && item.props){
          item.props.optionList=value
        }
      })
    }
  }
};
</script>
